package com.example.springsecuritydemo.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	//授权
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//链式编程
		//请求授权的规则
		http.authorizeRequests().antMatchers("/").permitAll()
				.antMatchers("/level1/**").hasRole("vip1")
				.antMatchers("/level2/**").hasRole("vip1")
				.antMatchers("/level3/**").hasRole("vip3");

		//没有权限默认到登录页面,
		//TODO 源码中读取默认跳转到"/login?error"
		//使用自定义的登录页面
		http.formLogin()
				.loginPage("/toLogin")
				.usernameParameter("name")
				.passwordParameter("password")
				.loginProcessingUrl("/login");


		//开启注销
		//TODO  默认注销路径  The default is that accessing the URL "/logout"
		http.logout().logoutSuccessUrl("/index");

		//防止网站攻击， get请求 无法使用
		http.csrf().disable(); //关闭

		//开启记住我功能 cookie,默认保存两周
		http.rememberMe().rememberMeParameter("remember");
	}

	//认证
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//数据正常从数据库读取
		auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
				.withUser("aa")
				.password(new BCryptPasswordEncoder().encode("123456"))
				.roles("vip1", "vip2")
		        .and().withUser("bb").
				password((new BCryptPasswordEncoder().encode("123456")))
				.roles("vip1","vip3");
	}
}
